<?php

if (!defined('BASEPATH')) {
    exit('No direct script access allowed');
}
global $data;

class Descargas extends CI_Controller {

    public function __construct() {
        parent::__construct();
        //redireccion segura
        if ($this->session->userdata('access') != 'grant') {
            redirect(base_url());
        }
        global $data;
        $data['responsableNombre'] = $this->session->userdata('responsableNombre');
        $data['place'] = 'descargas';
        $this->stats();
    }

    public function stats() {
        global $data;
        $data['acceso'] = $this->ciempies_model->lista_accesos();
        $data['tcolab'] = $this->ciempies_model->get_total('COLABORADOR');
        $data['ttutorial'] = $this->ciempies_model->get_total('TUTORIAL');
        $data['therramienta'] = $this->ciempies_model->get_total('HERRAMIENTA');
        $data['tuso_herramienta'] = $this->ciempies_model->get_total('uso_herramienta');
        $data['tvisita'] = $this->ciempies_model->get_total('visita');
    }

    public function menu($opc) {
        global $data;

        $formulario = $this->session->userdata('formulario');
        $data['coment_es'] = $formulario['coment_es'];
        $data['coment_en'] = $formulario['coment_en'];
        $data['link'] = $formulario['link'];
        $data['etiqueta'] = $formulario['etiqueta'];
        $data['version'] = $formulario['version'];
        $data['mensaje'] = $this->session->userdata('mensaje');


        $this->load->view('template/header', $data);
        $this->load->view('template/sidebar');
        switch ($opc) {
            case 'agregar':
                $this->load->view('descargas/content_alta');
                break;
            case 'modificar':
                $this->load->view('descargas/content_buscar');
                break;
        }
        $this->load->view('template/footer');

        //reiniciamos las variables
        $this->session->unset_userdata('formulario');
        $this->session->unset_userdata('mensaje');
    }

    public function liberarDescarga() {
        $this->form_validation->set_rules('coment_es', 'Descripcion es', 'required|trim');
        $this->form_validation->set_rules('coment_en', 'Descripcion en', 'required|trim');
        $this->form_validation->set_rules('link', 'Link', 'required|trim|xss_clean');
        $this->form_validation->set_rules('etiqueta', 'Etiqueta', 'required|trim|xss_clean');
        $this->form_validation->set_rules('version', 'Version', 'required|trim|xss_clean');

        $this->form_validation->set_error_delimiters('  <div class="alert alert-error" style="margin-top: 16px;">
                                                        <button type="button" class="close" data-dismiss="alert">×</button>
                                                        <strong> Cuidado! </strong>', '</div>');
        $this->form_validation->set_message('required', 'Hay campos vacios');

        //verificamos formulario en busca de errores de ususario
        if (!($this->input->post('liberarVersion') && $this->form_validation->run())) {

            $formulario = array(
                'coment_es' => $this->input->post('coment_es'),
                'coment_en' => $this->input->post('coment_en'),
                'link' => $this->input->post('link'),
                'etiqueta' => $this->input->post('etiqueta'),
                'version' => $this->input->post('version')
            );

            $this->session->set_userdata('formulario', $formulario);
            $this->session->set_userdata('mensaje', $this->form_validation->error('coment_es'));
            $this->session->set_userdata('mensaje', $this->form_validation->error('coment_en'));
            $this->session->set_userdata('mensaje', $this->form_validation->error('link'));
            $this->session->set_userdata('mensaje', $this->form_validation->error('version'));
            $this->session->set_userdata('mensaje', $this->form_validation->error('etiqueta'));

            redirect(base_url() . 'descargas/menu/agregar');
        }
        //formulario correcto, subimos la imagen
        $config['upload_path'] = './assets/uploads/';
        $config['allowed_types'] = 'gif|jpg|png|jpeg';
        $config['max_size'] = '2048';
        $config['max_width'] = '3000';
        $config['max_height'] = '3000';
        $config['overwrite'] = FALSE;
        $config['remove_spaces'] = TRUE;
        $config['encrypt_name'] = TRUE;

        $this->load->library('upload', $config);
        //SI LA IMAGEN FALLA AL SUBIR MOSTRAMOS EL ERROR EN LA VISTA UPLOAD_VIEW
        if (!$this->upload->do_upload('file_col')) {

            $formulario = array(
                'coment_es' => $this->input->post('coment_es'),
                'coment_en' => $this->input->post('coment_en'),
                'link' => $this->input->post('link'),
                'version' => $this->input->post('version'),
                'etiqueta' => $this->input->post('etiqueta'));

            $errorMsj = '<div class="alert alert-error" style="margin-top: 16px;">
                        <button type="button" class="close" data-dismiss="alert">×</button>
                        <strong> Cuidado! </strong>' . $this->upload->display_errors() . '</div>';
            $this->session->set_userdata('mensaje', $errorMsj);
            $this->session->set_userdata('formulario', $formulario);

            redirect(base_url() . 'descargas/menu/agregar');
        }

        //la imagen se subio correctamente, procedemos con la insercion en la base
        $file_info = $this->upload->data();
        $this->_create_thumbnail($file_info['file_name'], FALSE, 'assets/uploads/descargas/');

        //el formulario esta correcto,aterrizamos las variables
        $id = $this->session->userdata('responsableID');
        $coment_es = $this->input->post('coment_es');
        $coment_en = $this->input->post('coment_en');
        $link = $this->input->post('link');
        $etiqueta = $this->input->post('etiqueta');
        $version = $this->input->post('version');

        //añadimos a la base
        $this->ciempies_model->liberarDescarga($coment_es, $coment_en, $link, $version, $etiqueta, $id, $file_info['file_name']);

        //las imagenes se subieron correctamente
        $formulario = array(
            'coment_es' => '',
            'coment_en' => '',
            'link' => '',
            'version' => '',
            'etiqueta' => '');

        $this->session->set_userdata('mensaje', '<div class="alert alert-success" style="margin-top: 16px;">
                                                    <button type="button" class="close" data-dismiss="alert">×</button>
                                                    <strong> Bien! </strong> la descarga se guardó con éxito. </div>');
        $this->session->set_userdata('formulario', $formulario);

        redirect(base_url() . 'descargas/menu/agregar');
    }

    //FUNCIÓN PARA CREAR LA MINIATURA A LA MEDIDA QUE LE DIGAMOS
    public function _create_thumbnail($filename, $ratio, $destino) {
        $config['image_library'] = 'gd2';

        //CARPETA EN LA QUE ESTÁ LA IMAGEN A REDIMENSIONAR
        $config['source_image'] = 'assets/uploads/' . $filename;
        $config['create_thumb'] = FALSE;
        $config['maintain_ratio'] = $ratio;

        //CARPETA EN LA QUE GUARDAMOS LA MINIATURA
        $config['new_image'] = $destino;
        $config['width'] = 320;
        $config['height'] = 240;
        $this->load->library('image_lib');
        $this->image_lib->initialize($config);
        $this->image_lib->resize();
        //borramos la original

        unlink($config['source_image']);
    }

    public function buscarDescarga() {
        $p = $this->input->post('tag');
        $data['descarga'] = $this->ciempies_model->buscarDescarga($p);
        $this->load->view('descargas/lista_descargas', $data);
    }

    public function eliminarDescarga($key) {
        $filename = $this->ciempies_model->eliminarDescarga($key);
        unlink('assets/uploads/descargas/' . $filename->URL);
        $this->session->set_userdata('mensaje', '<div class="alert">
                                                    <button type="button" class="close" data-dismiss="alert">×</button>
                                                    <strong>Borrado</strong> terminado.  </div>');
        redirect(base_url() . 'descargas/menu/modificar');
    }

    public function modificarDescarga($id) {
        global $data;
        $data['mensaje'] = $this->session->userdata('mensaje');
        $descarga = $this->ciempies_model->datosDescarga($id);

        $data['id'] = $descarga->ID;
        $data['coment_es'] = $descarga->ES;
        $data['coment_en'] = $descarga->EN;
        $data['link'] = $descarga->FILEURL;
        $data['version'] = $descarga->DOWNLOADNAME;
        $data['etiqueta'] = $descarga->ETIQUETA;
        $data['filename'] = $descarga->FILENAME;


        //carga de vistas
        $this->load->view('template/header', $data);
        $this->load->view('template/sidebar');
        $this->load->view('descargas/content_editar');
        $this->load->view('template/footer');

        //reiniciamos las variables 
        $this->session->unset_userdata('mensaje');
    }

    public function actualizarDescarga() {
        $this->form_validation->set_rules('coment_es', 'Descripcion es', 'required|trim');
        $this->form_validation->set_rules('coment_en', 'Descripcion en', 'required|trim');
        $this->form_validation->set_rules('link', 'Link', 'required|trim|xss_clean');
        $this->form_validation->set_rules('etiqueta', 'Etiqueta', 'required|trim|xss_clean');
        $this->form_validation->set_rules('version', 'Version', 'required|trim|xss_clean');

        $this->form_validation->set_error_delimiters('<div class="error">', '</div>');
        $this->form_validation->set_message('required', 'Hay campos vacios');

        //verificamos formulario en busca de errores de ususario
        if (!($this->input->post('liberarVersion') && $this->form_validation->run())) {

            $this->session->set_userdata('mensaje', '<div class="alert alert-error" style="margin-top: 16px;">
                                                        <button type="button" class="close" data-dismiss="alert">×</button>
                                                        <strong> Cuidado! </strong> Hay errores en el formulario  </div>');
            redirect(base_url() . 'descargas/modificarDescarga/' . $this->input->post('id'));
        }
        //formulario correcto, subimos la imagen
        $config['upload_path'] = './assets/uploads/';
        $config['allowed_types'] = 'gif|jpg|png|jpeg';
        $config['max_size'] = '2048';
        $config['max_width'] = '3000';
        $config['max_height'] = '3000';
        $config['overwrite'] = FALSE;
        $config['remove_spaces'] = TRUE;
        $config['encrypt_name'] = TRUE;

        $this->load->library('upload', $config);
        //SI LA IMAGEN FALLA AL SUBIR MOSTRAMOS EL ERROR EN LA VISTA UPLOAD_VIEW
        if (!$this->upload->do_upload('file_col')) {

            $formulario = array(
                'coment_es' => $this->input->post('coment_es'),
                'coment_en' => $this->input->post('coment_en'),
                'link' => $this->input->post('link'),
                'version' => $this->input->post('version'),
                'etiqueta' => $this->input->post('etiqueta'),
                'filename' => $this->input->post('filename'),
                'id' => $this->input->post('id'));

            $errorMsj = '<div class="alert alert-error" style="margin-top: 16px;">
                        <button type="button" class="close" data-dismiss="alert">×</button>
                        <strong> Cuidado! </strong>' . $this->upload->display_errors() . '</div>';

            if ($this->upload->display_errors() == '<p>You did not select a file to upload.</p>') {

                //la iamgen no cambio, se actualizan los campos con los nuevos datos
                $this->ciempies_model->actualizarDescarga($formulario);

                $this->session->set_userdata('mensaje', '<div class="alert alert-success" style="margin-top: 16px;">
                                                        <button type="button" class="close" data-dismiss="alert">×</button>
                                                        <strong>Bien!</strong> Descarga actualizada correctamente </div>');
                redirect(base_url() . 'descargas/modificarDescarga/' . $this->input->post('id'));
            }
            $this->session->set_userdata('mensaje', $errorMsj);
            $this->session->set_userdata('formulario', $formulario);

            redirect(base_url() . 'descargas/modificarDescarga/' . $this->input->post('id'));
        }

        //la imagen se subio correctamente, procedemos con la insercion en la base
        $file_info = $this->upload->data();
        $this->_create_thumbnail($file_info['file_name'], FALSE, 'assets/uploads/descargas/');

        //el formulario esta correcto,aterrizamos las variables
        $formulario = array(
            'coment_es' => $this->input->post('coment_es'),
            'coment_en' => $this->input->post('coment_en'),
            'link' => $this->input->post('link'),
            'version' => $this->input->post('version'),
            'etiqueta' => $this->input->post('etiqueta'),
            'filename' => $file_info['file_name'],
            'id' => $this->input->post('id'));

        //añadimos a la base
        $this->ciempies_model->actualizarDescarga($formulario);
        //eliminamos imagen pasada
        unlink('assets/uploads/descargas/' . $this->input->post('filename'));

        $this->session->set_userdata('mensaje', '<div class="alert alert-success" style="margin-top: 16px;">
                                                <button type="button" class="close" data-dismiss="alert">×</button>
                                                <strong> Bien! </strong> Descarga actualizada correctamente </div>');
        redirect(base_url() . 'descargas/modificarDescarga/' . $this->input->post('id'));
    }

}
